package com.ruoyi.driver.controller;

import java.io.InputStream;
import java.util.*;
import java.io.IOException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.TimeUnit;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.hutool.core.util.RandomUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.ruoyi.driver.entity.LifeCallbackParam;
import com.ruoyi.driver.utils.HttpUtils;
import com.ruoyi.driver.utils.MD5Utils;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.log.annotation.Log;
import com.ruoyi.common.log.enums.BusinessType;
import com.ruoyi.common.security.annotation.RequiresPermissions;
import com.ruoyi.driver.domain.TbDriver;
import com.ruoyi.driver.service.ITbDriverService;
import com.ruoyi.common.core.web.controller.BaseController;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.core.utils.poi.ExcelUtil;
import com.ruoyi.common.core.web.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;
import sun.misc.BASE64Encoder;


/**
 * 司机Controller
 *
 * @author wuxiao
 * @date 2024-08-19
 */
@RestController
@RequestMapping("/settled")
public class TbDriverController extends BaseController
{
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private ExecutorService threadPool;


    @Autowired
    private ITbDriverService tbDriverService;

    @Autowired
    StringRedisTemplate stringRedisTemplate;
    @Autowired
    private ExecutorService executorService;



    @PostMapping("/sendCode")
    public AjaxResult sendCode(){
        String code = RandomUtil.randomNumbers(4);
        stringRedisTemplate.opsForValue().set("code",code,10, TimeUnit.MINUTES);
        return AjaxResult.success(code);
    }






    @PostMapping("/upload")
    @ResponseBody
    public Map upload(MultipartFile file) throws IOException {
        String timestamp = System.currentTimeMillis() + "";
        String sign = DigestUtils.md5Hex("gSPhmyV8uvf4ogQ6&" + timestamp + "&gSPhmyV8uvf4ogQ6i86esvW0YeGRjORP");
        InputStream inputStream = file.getInputStream();
        Runnable runnable = new Runnable(){
            @Override
            public void run() {
                System.out.println("runnable-----开始");
                //获取文件原始名并生成新的文件名。
                String filename = file.getOriginalFilename();
                String picName = UUID.randomUUID().toString() + filename.substring(filename.lastIndexOf("."));

                //使用阿里云OSS SDK创建客户端。
                OSS oss = new OSSClientBuilder().build("https://oss-cn-beijing.aliyuncs.com",
                        "LTAI5tNPGsF52sNLgLpa2fJL",
                        "YfPvM8xnfWOE05f2vQMiNERyNLq2Am");
                //将输入流中的数据上传到OSS存储桶。
                oss.putObject("ruoyibrand","idcard/"+ picName, inputStream);
                //关闭OSS客户端连接。
                oss.shutdown();
                System.out.println("runnable-----结束");
            }
        };
        //这行代码将 runnable 任务提交给 threadPool 线程池以便异步执行
        threadPool.submit(runnable);

        byte[] data = new byte[inputStream.available()];
        inputStream.read(data);

        //将字符集转换成功bas字符串
        BASE64Encoder encoder = new BASE64Encoder();
        String encode = encoder.encode(data);

        String ocrUrl = "https://api.shumaidata.com/v2/idcard/ocr";
        //httpClient   restTemplate
        HttpClient httpClient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(ocrUrl);
        List<NameValuePair> list = new ArrayList<NameValuePair>();
        list.add(new BasicNameValuePair("appid","gSPhmyV8uvf4ogQ6"));
        list.add(new BasicNameValuePair("timestamp",timestamp));
        list.add(new BasicNameValuePair("sign",sign));
        list.add(new BasicNameValuePair("image",encode));


        Map info = null;
        HttpEntity entity = new UrlEncodedFormEntity(list);
        httpPost.setEntity(entity);
        HttpResponse response = httpClient.execute(httpPost);
        String json = EntityUtils.toString(response.getEntity(), "UTF-8");
        System.out.println(json);
        Map map = JSONObject.parseObject(json, Map.class);
        if((Boolean) map.get("success")==true && (Integer)map.get("code")==200){
            Map res = (Map)map.get("data");
            info = (Map)res.get("info");
        }

        return info;
    }

    @RequestMapping("/face")
    public void toPage(HttpServletRequest request, HttpServletResponse response, @RequestParam String mobile) throws IOException {
        //进行客户端校验，判断是否来源于PC，来源于PC拒绝
        String user_agent = request.getHeader("User-Agent");
        System.out.println(user_agent);
//		//移动端操作系统：iPhone Android （黑莓 鸿蒙 windowsPphone 塞班）
        if(user_agent.indexOf("Android")<0&&user_agent.indexOf("iPhone")<0){
//			return "校验失败";
        }
        String callbackUrl = "http://czh.free.idcfengye.com"+"/driver/result";
        //由天眼数聚识别页面，识别完成后，需要跳转回我们提供的一个页面。returnUrl就是这个用来接收请求的页面路径
        String returnUrl = "http://localhost:8080/pages/driver/wait";
        String timestamp = System.currentTimeMillis() + "";
        String sign = this.tianyanSign(timestamp);

        String url = "https://lifeh5.shumaidata.com/index.html#/?appid="
                +"gSPhmyV8uvf4ogQ6"+"&callbackUrl="+callbackUrl+
                "&returnUrl="+returnUrl+"&complexity=2&timestamp="+timestamp+
                "&sign="+sign+"&uid="+mobile+"&title=didicar";
        response.sendRedirect(url);
    }

    private String tianyanSign(String time){
        return DigestUtils.md5Hex("gSPhmyV8uvf4ogQ6"+"&"+time+"&"+"gSPhmyV8uvf4ogQ6i86esvW0YeGRjORP");
    }

    @GetMapping("/mobileCheck/{mobile}")
    @ResponseBody
    public Boolean mobileCheck(@PathVariable String mobile,@RequestBody Map map){
        String timestamp = System.currentTimeMillis() + "";
        //司机的身份证正面信息
        Map frontInfo = JSON.parseObject(map.get("frontInfo").toString(), Map.class);
        //司机的反面身份证信息
        Map backInfo = JSON.parseObject(map.get("backInfo").toString(), Map.class);

//		String idcardBackUrl = (String) map.get("idcardBackUrl");
//		String idcardFrontUrl = (String) map.get("idcardFrontUrl");
        //司机的姓名
        String name = (String) frontInfo.get("name");

        //司机的身份证
        String idcard = (String) frontInfo.get("number");

        String url = "https://api.shumaidata.com/v4/mobile_three/transfer";
        String sign = MD5Utils.encrypt("gSPhmyV8uvf4ogQ6&" + timestamp + "&gSPhmyV8uvf4ogQ6i86esvW0YeGRjORP");
        System.out.println("sign: "+sign);

        Map<String,Object> params = new HashMap<String,Object>();
        params.put("appid","gSPhmyV8uvf4ogQ6");
        params.put("timestamp",timestamp);
        params.put("sign",sign);
        params.put("name", name);
        params.put("mobile", mobile);
        params.put("idcard", idcard );

        //请下载 HttpUtils文件，地址为 https://file.tianyandata.cn/demo/utils/HttpUtils.java
        String result = HttpUtils.get(url,null,params);
        System.out.println(result);
        Map resultMap = JSONObject.parseObject(result, Map.class);
        Map data = (Map) resultMap.get("data");
        if(data.get("result").equals("0")){
            //将手机号和身份信息存储起来
            redisTemplate.opsForHash().putAll(mobile,map);
            return true;
        }else{
            return false;
        }
    }

    @RequestMapping("/result")
    @ResponseBody
    public void result(@RequestBody LifeCallbackParam param) throws IOException {
        Map resultInfo = param.getInfo();
        Integer code = (Integer) resultInfo.get("code");
        if(code!=200){
            return;
        }


        //根据uid（手机号）查询Redis 获取身份证号和姓名
        String mobile = param.getUid();
        Map info = redisTemplate.opsForHash().entries(mobile);
        //根据图片ID拿到图片流,is->base64
        Map data = (Map) resultInfo.get("data");
        String imageId = (String) data.get("feature_image_id");
        String picUrl = "https://api.shumaidata.com/v2/life/check/image?imageId="+imageId;
        System.out.println(picUrl);
        //如果结果是成功，则需要判断是否认证合一
        //从活体检测的结果中，取出活体检测时候的照片


        String name = (String) info.get("name");
        System.out.println(name);
        String idcard = (String) info.get("number");
        System.out.println(idcard);
        //接口地址
        String url = "https://api.shumaidata.com/v4/face_id_card/compare";

        String timestamp = System.currentTimeMillis() + "";
        String sign = this.tianyanSign(timestamp);

        Map<String,String> headers = new HashMap<String,String>();
        headers.put("Content-Type","application/x-www-form-urlencoded");

        Map<String,Object> params = new HashMap<String,Object>();
        params.put("appid","gSPhmyV8uvf4ogQ6");
        params.put("timestamp",timestamp);
        params.put("sign",sign);
        params.put("name", name);
        params.put("idcard", idcard);
        params.put("url", picUrl);


        String result = HttpUtils.postForm(url,headers,params);
        Map map = JSONObject.parseObject(result, Map.class);
        Map resultData = (Map) map.get("data");
        //0.45分以上为同一人
        if(resultData.get("msg").equals("系统判断为同一人")){
//            tbUserService.updateUserStatus(mobile,1);

            redisTemplate.opsForValue().set("res"+mobile,"true");
        }else{
            redisTemplate.opsForValue().set("res"+mobile,"false");
        }

    }

    @RequestMapping("getFinalResult")
    @ResponseBody
    public Boolean getFinalResult(String mobile){
        String result = (String) redisTemplate.opsForValue().get("res" + mobile);
        return result.equals("true");
    }
    @PostMapping("/save")
    public AjaxResult save(@RequestBody TbDriver tbDriver){

        return tbDriverService.selectTbDriver(tbDriver);
    }


    /**
     * 查询司机列表
     */
    @RequiresPermissions("settled:driver:list")
    @GetMapping("/list")
    public TableDataInfo list(TbDriver tbDriver)
    {
        startPage();
        List<TbDriver> list = tbDriverService.selectTbDriverList(tbDriver);
        return getDataTable(list);
    }

    /**
     * 导出司机列表
     */
    @RequiresPermissions("settled:driver:export")
    @Log(title = "司机", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, TbDriver tbDriver)
    {
        List<TbDriver> list = tbDriverService.selectTbDriverList(tbDriver);
        ExcelUtil<TbDriver> util = new ExcelUtil<TbDriver>(TbDriver.class);
        util.exportExcel(response, list, "司机数据");
    }

    /**
     * 获取司机详细信息
     */
    @RequiresPermissions("settled:driver:query")
    @GetMapping(value = "/{driverId}")
    public AjaxResult getInfo(@PathVariable("driverId") Long driverId)
    {
        return AjaxResult.success(tbDriverService.selectTbDriverByDriverId(driverId));
    }

    /**
     * 新增司机
     */

    @Log(title = "司机", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    public AjaxResult add(@RequestBody TbDriver tbDriver)
    {
        return toAjax(tbDriverService.insertTbDriver(tbDriver));
    }

    /**
     * 修改司机
     */
    @RequiresPermissions("settled:driver:edit")
    @Log(title = "司机", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody TbDriver tbDriver)
    {
        return toAjax(tbDriverService.updateTbDriver(tbDriver));
    }

    /**
     * 删除司机
     */
    @RequiresPermissions("settled:driver:remove")
    @Log(title = "司机", businessType = BusinessType.DELETE)
	@DeleteMapping("/{driverIds}")
    public AjaxResult remove(@PathVariable Long[] driverIds)
    {
        return toAjax(tbDriverService.deleteTbDriverByDriverIds(driverIds));
    }
}
